package com.joymart.product.service;


import com.joymart.common.system.IdGenerator;
import com.joymart.common.utils.DatetimeUtils;
import com.joymart.product.model.Product;
import com.joymart.product.model.Stock;
import com.joymart.product.repo.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jdbc.core.JdbcAggregateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private JdbcAggregateTemplate jdbcAggregateTemplate;
    @Autowired
    private IdGenerator idGenerator;
    @Autowired
    private StockService stockService;

    public List<Product> findAllNotDeletedProducts  () {
        return productRepository.findByDeletedFalseOrderByIdDesc();
    }

    public List<String> findOnMarketProductIds(){
        return productRepository.findIdByDeletedFalseAndOnMarketTrue();
    }



    @Cacheable(value = "products", key = "#productId")
    public Product findByIdFromCache(String productId) {
        return this.findById(productId);
    }

    public Product findById(String productId) {
        return productRepository.findById(productId).orElse(null);
    }


    @Transactional
    @CacheEvict(value = "products", key = "#product.id")
    public void modify(Product product) {
        productRepository.save(product);
    }

    @Transactional
    public void create(Product product, int initialStock) {
        product.setId(idGenerator.next());
        product.setDeleted(false);
        product.setOnMarket(false);
        product.setCreatedAt(DatetimeUtils.now());
        jdbcAggregateTemplate.insert(product);

        Stock stock = new Stock();
        stock.setProductId(product.getId());
        stock.setQuantity(initialStock);
        jdbcAggregateTemplate.insert(stock);
    }

    @Transactional
    @CacheEvict(value = "products", key = "#id")
    public void changeStatus(String id, boolean targetStatus) {
        Product product = findById(id);
        if(targetStatus== product.isOnMarket()){
            return;
        }
        product.setOnMarket(targetStatus);
        if(targetStatus == true){
            product.getMeta().put("lastOnMarketAt", DatetimeUtils.now());
        }
        productRepository.save(product);
    }

    @Transactional
    public void adjustStock(String id, Integer delta) {
        if(delta == 0) return;
        stockService.increaseStock(id, delta);
    }
}
